package com.eqdd.annotation.api;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author hiphonezhu@gmail.com
 * @version [CompilerAnnotation, 17/6/20 11:28]
 */

public class DealCodeInjector {
    public static Object register(Object host, Class clazz) {

        try {
            String classFullName = host.getClass().getName() + "$$DealCodeInjector";
            Class<?> aClass = Class.forName(classFullName);
            Constructor<?> constructor = aClass.getConstructor(Object.class);
            Object o = constructor.newInstance(host);
            Method getDefault = clazz.getDeclaredMethod("getDefault");
            Method register = clazz.getDeclaredMethod("register", Object.class);
            Object invoke = getDefault.invoke(null);
            register.invoke(invoke, o);
            return o;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void unregister(Object host, Class clazz, Object object) {
        try {
//            String classFullName = host.getClass().getName() + "$$DealCodeInjector";
//            Class<?> aClass = Class.forName(classFullName);
            Method getDefault = clazz.getDeclaredMethod("getDefault");
            Method unregister = clazz.getDeclaredMethod("unregister", Object.class);
            Object invoke = getDefault.invoke(null);
            unregister.invoke(invoke, object);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }


}
